import { ForwardedRef, forwardRef, memo } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Control, Controller } from 'react-hook-form';
import {
  Form,
  FormItemProps,
  Radio,
  RadioGroupProps,
} from 'antd';
import QueueAnim from 'rc-queue-anim';
import { RadioItem } from '@/components/typing';

const RxRadio = forwardRef<
  any,
  PropsWithChildren<
    {
      name: string;
      control: Control<any>;
      radioItem: RadioItem[];
      item?: FormItemProps;
    } & Partial<RadioGroupProps>
  >
>(({ radioItem, name, control, item, ...rest }, ref) => {
  const animateConfig = [{ opacity: [1, 0], translateY: [0, 5] }];

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => (
        <div ref={ref}>
          <Form.Item {...item}>
            <Radio.Group {...field} {...rest}>
              {radioItem.map((item) => {
                return <Radio value={item.value} key={item.value}>{item.label}</Radio>;
              })}
            </Radio.Group>

            <QueueAnim animConfig={animateConfig}>
              {fieldState.error && (
                <p
                  className={'absolute leading-6 text-xs text-red-400'}
                  key={fieldState.error.message}
                >
                  {fieldState.error?.message}
                </p>
              )}
            </QueueAnim>
          </Form.Item>
        </div>
      )}
    />
  );
});

export default memo(RxRadio);
